import { Dish } from '@/types/dish';
import { Image } from 'react-native';

// 定义API接口返回的数据类型
interface ApiDish {
  id: string;
  key: string;
  code: number;
  name: string;
  price: number;
  image: string;
  tags: string[];
}

// 根据tags判断category，现在返回数组
const getCategories = (tags: string[]): string[] => {
  const categories: string[] = [];
  
  // 添加到全部分类
  categories.push('all');
  
  // 根据tags添加对应分类
  if (tags.includes('素菜')) categories.push('vegetable');
  if (tags.includes('甜食')) categories.push('dessert');
  if (tags.includes('荤菜') || (!tags.includes('素菜') && !tags.includes('甜食'))) {
    categories.push('meat');
  }
  
  return categories;
};

// 修改转换函数，将category改为categories数组
const convertApiDishToDish = (apiDish: ApiDish): Dish => {
  return {
    id: apiDish.id,
    name: apiDish.name,
    price: apiDish.price,
    description: '', // API中没有description字段，可以留空或根据需要设置
    image: { uri: `http://116.205.137.46${apiDish.image}` }, // 构建完整的图片URL
    categories: getCategories(apiDish.tags), // 现在返回categories数组
    tags: apiDish.tags,
  };
};

// 缓存获取的菜品数据
let cachedDishes: Dish[] = [];

// 从API获取菜品数据
export const fetchDishes = async (): Promise<Dish[]> => {
  try {
    const response = await fetch('http://116.205.137.46/api/dishes');
    if (!response.ok) {
      throw new Error('Failed to fetch dishes');
    }
    const apiDishes: ApiDish[] = await response.json();
    cachedDishes = apiDishes.map(convertApiDishToDish);
    return cachedDishes;
  } catch (error) {
    console.error('Error fetching dishes:', error);
    throw error;
  }
};

// 修改获取指定分类的菜品函数
export const getDishsByCategory = (categoryId: string): Dish[] => {
  try {
    return cachedDishes.filter(dish => dish.categories.includes(categoryId));
  } catch (error) {
    console.error('Error loading dishes:', error);
    return [];
  }
};

// 预加载图片
export const preloadImages = async () => {
  try {
    const imagePromises = cachedDishes.map(dish => {
      if (typeof dish.image === 'string') {
        return Image.prefetch(dish.image);
      }
      return Promise.resolve();
    });
    await Promise.all(imagePromises);
  } catch (error) {
    console.error('Error preloading images:', error);
    throw error;
  }
};